package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.constants.WmNewsMessageConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.threadLocal.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;

import com.heima.wemedia.service.WmNewsTaskService;
import javafx.animation.Animation;
import org.apache.commons.lang3.StringUtils;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.health.Status;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired(required = false)
    private WmNewsTaskService wmNewsTaskService;

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;
    /**
     * 查询文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        //1.参数校验
            //分页页码校验
            dto.checkParam();
        //2.执行分页查询
        IPage<WmNews> ipage=new Page<>(dto.getPage(),dto.getSize());

        LambdaQueryWrapper<WmNews> queryWrapper=new LambdaQueryWrapper<>();
        //状态条件
        if(dto.getStatus()!=null){
            queryWrapper.eq(WmNews::getStatus,dto.getStatus());
        }
        //频道id条件
        if(dto.getChannelId()!=null){
            queryWrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }
        //关键字条件
        if(StringUtils.isNotBlank(dto.getKeyword())){
            queryWrapper.like(WmNews::getTitle,dto.getKeyword());
        }
        //时间条件
        if(dto.getBeginPubdate()!=null && dto.getEndPubdate()!=null){
            queryWrapper.between(WmNews::getPublishTime,dto.getBeginPubdate(),dto.getEndPubdate());
        }
        //用户id条件
        queryWrapper.eq(WmNews::getUserId, WmThreadLocalUtil.getWmUser().getId());

        IPage<WmNews> resultPage = page(ipage, queryWrapper);

        //3.返回数据
        ResponseResult result=new PageResponseResult(dto.getPage(),dto.getSize(), (int) resultPage.getTotal());
        result.setData(resultPage.getRecords());
        return result;
    }

    /**
     * 发布文章-保存，修改和保存草稿
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submit(WmNewsDto dto) {
        //1.参数校验
        if(dto.getContent()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"当前内容为空");
        }

        //如果是自动的话，重新赋值为空
        if(dto.getType()==-1){
            dto.setType(null);
        }

        //2.保存和修改文章 wm_news
        WmNews wmNews=new WmNews();
        BeanUtils.copyProperties(dto,wmNews);
        //对封面图片处理
        wmNews.setImages(StringUtils.join(dto.getImages(),","));
        //对时间处理
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        //用户id处理
        wmNews.setUserId(WmThreadLocalUtil.getWmUser().getId());

        saveOrUpdateWmNews(wmNews);

        //3.判断是否是草稿
            //如果是草稿的话，此程序终止
        if(dto.getStatus()==0){
            return ResponseResult.okResult(AppHttpCodeEnum.CAOGAO_STATUS);
        }
            //如果不是草稿的话，就是提交审核

        //3.5。从内容中抽取图片的集合
         List<String> imageUrlList= getFromImageContent(wmNews);
        //4.关联内容中的图片与文章关系
        contentImageToNews(wmNews, imageUrlList, WemediaConstants.WM_CONTENT_REFERENCE);

        //5.关联封面中的图片与文章关系
        fengmianImageToNews(wmNews,dto,imageUrlList,WemediaConstants.WM_COVER_REFERENCE);

        //异步调用文章审核业务
        //调用延迟任务服务的添加方法
        wmNewsTaskService.addNewsToTask(wmNews.getId(), dto.getPublishTime());



        //6.返回数据
        return ResponseResult.okResult("发布成功");
    }

    /**
     * 文章的上下架
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        //8.参数效验
        if (dto.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //根据id查询文章
        WmNews wmNews = getById(dto.getId());
        if (wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"当前文章不存在");
        }
        //2.查询是否已经是发布状态
        if (wmNews.getStatus()!=WmNews.Status.PUBLISHED.getCode()){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"当前文章是发布状态,不可以操作");
        }
        //3.修改文章状态
        wmNews.setEnable(dto.getEnble());
        boolean flag = updateById(wmNews);

        //4.发布消息
        if (flag){
            Map messageMap=new HashMap();
            messageMap.put("articleId",wmNews.getArticleId());
            messageMap.put("enable",wmNews.getEnable());
            kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC,JSON.toJSONString(messageMap));
        }

        return ResponseResult.okResult("文章操作成功");

    }

    /**
     * 抽取的第四个方法，关联内容中的图片与文章关系
     * @param wmNews
     * @param imageUrlList 内容中的图片地址集合
     * @param type 0内容引用 1表示封面引用
     */
    private void contentImageToNews(WmNews wmNews, List<String> imageUrlList, Short type) {
        //4.1 根据素材url集合获取对应的素材id集合
        List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, imageUrlList));
        List<Integer> imageIdList = wmMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());
        //4.2 插入中间表
        wmNewsMaterialMapper.saveRelations(imageIdList, wmNews.getId(), type);
    }

    /**
     * 抽取的第三个方法，关联封面中的图片与文章关系
     * @param wmNews
     * @param dto
     * @param imageUrlList 内容中图片集合
     */
    private void fengmianImageToNews(WmNews wmNews,WmNewsDto dto,List<String>imageUrlList,Short type) {
        //5.1先获取封面中的图片
        List<String> images = dto.getImages();

        //判段如果说是自动化的话，
        if(dto.getType()==null){
            //从内容中获取图片作为封面图片
            if(imageUrlList.size()>=1 && imageUrlList.size()<3){//单图
                images=imageUrlList.stream().limit(1).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
            }else
            if(imageUrlList.size()>=3){//多图
                images=imageUrlList.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
            }else{
                //无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }

            //执行修改wm_news表
            wmNews.setImages(StringUtils.join(images,","));
            updateById(wmNews);
        }
        //4.1 根据素材url集合获取对应的素材id集合
        contentImageToNews(wmNews, images, type);
    }

    /**
     * 第二个抽取的方法，从内容中抽取图片的集合
     * @param wmNews
     * @return
     */
    private List<String> getFromImageContent(WmNews wmNews) {
        List<String> imageList=new ArrayList<>();

        //1.获取文章内容
        String content = wmNews.getContent();
        //把字符串类型转成List<Map>
        List<Map> contentList = JSONArray.parseArray(content, Map.class);
        if(contentList!=null){
            for (Map map : contentList) {
                //如果是图片
                if(map.get("type").equals("image")){
                    String imageUrl = (String) map.get("value");
                    imageList.add(imageUrl);
                }
            }
        }
        return imageList;
    }

    /**
     * 抽取的第一个方法，保存和修改文章
     * @param wmNews
     */
    private void saveOrUpdateWmNews(WmNews wmNews) {
        if(wmNews.getId()!=null){
            //如果是修改的话，则先删除中间表，然后再修改wm_news表
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
            updateById(wmNews);
        }else{
            //如果是保存的话，则直接插入数据到wm_news表
            save(wmNews);
        }
    }
}
